<template>
  <view class="login">
    <view class="login-form">
      <form @submit="formSubmit" @reset="formReset">
        <view class="login-form__item"><input class="login-form__item-input" name="username" placeholder="请输入用户名" /></view>
        <view class="login-form__item"><input class="login-form__item-input" name="password" password placeholder="请输入密码" /></view>
        <view class="login-form__item">
          <input class="login-form__item-code" name="code" placeholder="请输入验证码" />
          <image class="login-form__item-codeimg" :src="code" @click="getVerify"></image>
        </view>
        <input name="key" :value="key" hidden />
        <view class="login-form__btn">
          <button class="login-form__btn-button" formType="submit">登录</button>
          <button class="login-form__btn-button" type="default" formType="reset">重置</button>
        </view>
      </form>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
export default {
  data() {
    return {
      key: '',
      code: ''
    }
  },
  methods: {
    ...mapActions('user', ['login', 'verify']),
    getVerify() {
      this.verify().then(res => {
        console.log(res, 'code')
        const { imgkey, base64img } = res.data
        this.key = imgkey
        this.code = base64img
      })
    },
    formSubmit: function (e) {
      const { username, password, code, key } = e.detail.value
      this.login({
        username,
        password,
        code,
        key
      }).then(res => {
        if (res.code === 1) {
          uni.setStorageSync('user', res.data)
          uni.reLaunch({
            url: '/pages/people/index'
          })
        }
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
      })
      console.log('form发生了submit事件，携带数据为：' + JSON.stringify(e.detail.value))
    },
    formReset: function (e) {
      console.log('清空数据')
    }
  },
  mounted() {
    this.getVerify()
  }
}
</script>

<style lang="scss" scoped>
.login {
  padding: 20rpx;
  &-form {
    margin-top: 40rpx;
    &__item {
      display: flex;
      padding: 30rpx 0;
      border-bottom: 1px solid #f0f0f0;
      &-code {
        width: 600rpx;
      }
      &-codeimg {
        margin: -10rpx 0 -20rpx 20rpx;
        width: 130rpx;
        height: 65rpx;
      }
    }
    &__btn {
      margin-top: 40rpx;
      display: flex;
      justify-content: space-between;
      &-button {
        flex: 1;
        margin-right: 20rpx;
        height: 80rpx;
        line-height: 80rpx;
        background-color: #f60;
        color: #fff;
        &::after {
          display: none;
        }
        &:last-child {
          margin-right: 0;
          background-color: #999;
        }
      }
    }
  }
}
</style>
